package god.dream.user.service;

import god.dream.comment.dao.CommentDAO;
import god.dream.comment.model.Comment;
import god.dream.user.dao.UserDAO;
import god.dream.user.model.User;

import java.util.List;

import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

public class UserServiceImpl implements UserService {
	
	
	private UserDAO userDAO;
	private CommentDAO commentDAO;
	private TransactionTemplate transactionTemplate;
	
	public int addUser(User user) {
		return userDAO.insert(user);
	}

	public User findUser(int id) {
		return userDAO.findUser(id);
	}

	public List<User> findUserList() {
		return userDAO.findUserList();
	}

	public int removeUser(final int id) {
		Object deleteRes = transactionTemplate.execute(
		new TransactionCallback(){
			public Object doInTransaction(TransactionStatus status){
				try{
					List list = commentDAO.findCommentListWithUser(id);
					if(list != null){
						for(int i=0; i < list.size();i++){
							Comment comment = (Comment)list.get(i);
							commentDAO.delete(comment.getId());
						}
					}
					return userDAO.delete(id);					
				}catch(Exception ex){
					status.setRollbackOnly();
					return ex;
				}
			}
		});
		if (deleteRes instanceof Throwable) {
			return 0;
		}else{
			return (Integer)deleteRes;
		}
	}

	public int updateUser(User user) {
		return userDAO.update(user);
	}

	public UserDAO getUserDAO() {
		return userDAO;
	}

	public void setUserDAO(UserDAO userDAO) {
		this.userDAO = userDAO;
	}

	public CommentDAO getCommentDAO() {
		return commentDAO;
	}

	public void setCommentDAO(CommentDAO commentDAO) {
		this.commentDAO = commentDAO;
	}

	public TransactionTemplate getTransactionTemplate() {
		return transactionTemplate;
	}

	public void setTransactionTemplate(TransactionTemplate transactionTemplate) {
		this.transactionTemplate = transactionTemplate;
	}


}
